package com.pd.kit;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * Created by dong peng
 * DATE : 2016/12/18
 * TIME : 22:57.
 *
 * 借助dom4j处理xml文件数据与String类型转换
 */
public final class XmlKit {

    private XmlKit(){}

    /**
     * 只针对一层xml节点
     * 解析xml文件：xml标签的名字作为Map的key，xml标签的内容作为Map的value
     * @param fileName
     * @return
     * @throws DocumentException
     */
    public static Map<String,String> parseXml(String fileName) throws DocumentException {

        if(fileName == null || "".equals(fileName)) {
            throw new RuntimeException("xml文件解析失败：确认文件是否在classes目录下.............");
        }

        // 依赖dom4j的jar包解析xml数据
        String filePath = XmlKit.class.getResource("/").getPath()+fileName;
        File file = new File(filePath);
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(file);
        Map map = documentToMap(document);

        return  map;
    }

    /**
     * 将xml格式数据的字符串解析为Map类型，当然xml结构也只支持一层
     * @param text]
     * @return
     * @throws DocumentException
     */
    public static Map<String,String> toMap(String text) throws DocumentException {
        Document document = DocumentHelper.parseText(text);
        Map map = documentToMap(document);
        return map;
    }

    /**
     * map数据转换为xml格式的字符串
     * @param inParam
     * @return
     */
    public static  String toXmlStr(Map<String,String> inParam) {
        Set<Map.Entry<String, String>> entrySet = inParam.entrySet();
        StringBuilder stringBuilder = new StringBuilder();
        for(Map.Entry entry : entrySet) {
            stringBuilder.append("<"+entry.getKey()+"><![CDATA["+entry.getValue()+"]]</"+entry.getKey()+">");
        }

        return  "<xml>"+stringBuilder.toString()+"</xml>";
    }

    private static Map<String,String> documentToMap(Document document) {
        Map<String,String> resultMap = new HashMap();
        Element root = document.getRootElement();
        for(Iterator i = root.elementIterator(); i.hasNext(); ){
            Object obj = i.next();
            if(obj instanceof Element) {
                Element e = (Element) obj;
                resultMap.put(e.getName(),e.getText());
            }
        }

        return  resultMap;
    }

}
